package com.dominator.utils.mail;

import microsoft.exchange.webservices.data.EWSConstants;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
 
public class ExchangerServiceSSLVerify extends ExchangeService {
 
    public ExchangerServiceSSLVerify(ExchangeVersion requestedServerVersion) {
        super(requestedServerVersion);
    }
 
    @Override
    protected Registry<ConnectionSocketFactory> createConnectionSocketFactoryRegistry() {
        try {
            SSLContext sslContext = createSSL();
            return RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(EWSConstants.HTTP_SCHEME, PlainConnectionSocketFactory.INSTANCE)
                    .register(EWSConstants.HTTPS_SCHEME, new SSLConnectionSocketFactory(sslContext))
                    .build();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(
                    "Could not initialize ConnectionSocketFactory instances for HttpClientConnectionManager", e
            );
        }
    }
 
    private SSLContext createSSL() throws NoSuchAlgorithmException, KeyManagementException {
 
        //Secure Protocol implementation.
        SSLContext ctx = SSLContext.getInstance("SSL");
        //Implementation of a trust manager for X509 certificates
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs,
                                           String string) throws CertificateException {
            }
 
            @Override
            public void checkServerTrusted(X509Certificate[] xcs,
                                           String string) throws CertificateException {
            }
 
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        return ctx;
    }
}
